package cn.kbyue.demo.websocketdemo.config;

import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author XL
 * @version 0.1
 * @date 2022/6/11 9:59
 */
@Configuration
public class TomcatMultiPortConfig {

    @Value("${server.additional-ports}")
    private String additionalPorts;

    @Bean
    public TomcatServletWebServerFactory serverFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        Connector[] additionalConnectors = this.additionalConnector();
        if (additionalConnectors.length > 0) {
            factory.addAdditionalTomcatConnectors(additionalConnectors);
        }
        return factory;
    }

    private Connector[] additionalConnector() {
        if (StringUtils.isEmpty(additionalPorts)) {
            return new Connector[]{};
        }
        String[] ports = additionalPorts.split(",");
        List<Connector> connectors = new ArrayList<>();
        for (String port : ports) {
            Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
            connector.setScheme("http");
            connector.setPort(Integer.parseInt(port));
            connectors.add(connector);
        }
        return connectors.toArray(new Connector[]{});
    }

}
